package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.asm.Advice;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Slf4j
@Component
@Aspect
public class AutoFillAspect {

    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void pointCut() {}

    @Before("pointCut()")
    public void before(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Object[] args = joinPoint.getArgs();//获取运行到该处的所有参数对象以及参数对象的属性值
        Object arg = args[0];
        Class<?> aClass = arg.getClass();//约定取第一个参数作为Aop数据注入目标
        try {
            if (signature.getMethod().getAnnotation(AutoFill.class).value().equals(OperationType.INSERT)) {
                log.info("insert前置通知启动");
                Method createTimeMethod = aClass.getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method updateTimeMethod = aClass.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method createUserMethod = aClass.getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method updateUserMethod = aClass.getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

                createTimeMethod.invoke(arg,LocalDateTime.now());
                updateTimeMethod.invoke(arg,LocalDateTime.now());
                createUserMethod.invoke(arg,BaseContext.getCurrentId());
                updateUserMethod.invoke(arg,BaseContext.getCurrentId());

            }else if (signature.getMethod().getAnnotation(AutoFill.class).value().equals(OperationType.UPDATE)) {
                log.info("update前置通知启动");
                Method updateTimeMethod = aClass.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method updateUserMethod = aClass.getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                
                updateTimeMethod.invoke(arg,LocalDateTime.now());
                updateUserMethod.invoke(arg,BaseContext.getCurrentId());
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }

    }
}
